import os
from django.shortcuts import render
from django.views import View
from django import http

from django.conf import settings
from alipay import AliPay
from orders.models import OrderInfo
from meiduo_mall.utils.views import LoginRequiredJsonMixin
from meiduo_mall.utils.response_code import RETCODE
from .models import Payment
# Create your views here.


class PaymentStatusView(View):
    """保存订单支付结果"""

    def get(self, request):

        # 获取所有的查询参数
        query_dict = request.GET
        # 将查询参数转成dict
        data = query_dict.dict()
        # 从查询参数中提取并移除 sign, 不能参与签名验证
        signature = data.pop('sign')
        # 使用SDK对象, 调用通知验证接口函数, 得到验证结果
        # os.path.dirname(__file__)返回脚本的路径 os.path.abspath返回的是.py文件的绝对路径
        key_path = os.path.dirname(os.path.abspath(__file__))
        app_private_key_string = open(os.path.join(key_path, "keys\\app_private_key.pem")).read()
        alipay_public_key_string = open(os.path.join(key_path, "keys\\alipay_public_key.pem")).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 经行校验
        success = alipay.verify(data, signature)
        # 如果验证通过, 需要将支付宝的支付状态进行处理
        if success:
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存Payment模型数据
            try:
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_id
                )
            except Exception:
                return http.HttpResponseServerError('数据库存入失败')

            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id,
                                     status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )

            # 响应trade_id
            context = {
                'trade_id':trade_id
            }

            return render(request, 'pay_success.html', context)
        else:
            return http.HttpResponseForbidden('非法请求')


class PaymentView(LoginRequiredJsonMixin, View):
    """订单支付功能"""

    def get(self, request, order_id):
        user = request.user
        # os.path.dirname(__file__)返回脚本的路径 os.path.abspath返回的是.py文件的绝对路径
        key_path = os.path.dirname(os.path.abspath(__file__))

        # 接收和校验参数
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单信息错误')
        app_private_key_string = open(os.path.join(key_path, "keys\\app_private_key.pem")).read()
        alipay_public_key_string = open(os.path.join(key_path, "keys\\alipay_public_key.pem")).read()
        # 创建对接支付宝接口的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url, 如果采用同步机制就不传
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # 加密标准
            debug=settings.ALIPAY_DEBUG  # 指定是否是开发环境
        )
        # SDK对象对接支付宝支付的接口, 得到登录页的地址
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 订单编号
            total_amount=str(order.total_amount),  # 订单支付金额
            subject="美多商城%s" % order_id,  # 订单标题
            return_url=settings.ALIPAY_RETURN_URL,  # 同步通知的回调地址, 如果不是同步通知, 就不传
        )
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})
